
import torch
import torch.nn as nn
import torch.nn.functional as F
import data


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        self.dropout = nn.Dropout(0.5)
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 10, 5)
        self.conv2 = nn.Conv2d(10, 25, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(15 * 15, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 62)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        # print(f'x:{x},num_flat_features:{self.num_flat_features(x)}')
        # print(self.num_flat_features(x))

        x = x.view(-1, self.num_flat_features(x))
        # print('111111')
        x = F.relu(self.fc1(x))
        # print('222222')
        x = F.relu(self.fc2(x))
        # print('333333')
        x = self.fc3(x)
        # print('444444')
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

# net = Net()
# print(net)

import torch.optim as optim
import data
import torch


def train():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    net = Net()
    net.to(device)

    net = Net()
    opt = optim.SGD(net.parameters(), lr=0.01)
    epoch = 2000
    batch_size = 50
    trainloader = data.trainloader(batch_size)
    for e in range(epoch):
        for step, d in enumerate(trainloader):
            # print(f'step:{step}')
            data_cuda =  d["data"].to(device)
            # print(f'data_cuda:{data_cuda}')
            label_cuda = d["label"].to(device)
            # print(f'label_cuda:{label_cuda}')

            opt.zero_grad()
            out = net(data_cuda)
            lf = nn.CrossEntropyLoss()
            loss = lf(out, label_cuda)
            loss.backward()
            opt.step()
            if (e % 50 == 0):
                print("e : {} , step : {}, loss : {}".format(e, step, loss))
    torch.save(net.state_dict(),"./model/net.pt")
    torch.save(opt.state_dict(), "./model/opt.pt")

if (__name__ == "__main__"):
    train()

